using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using PepsiCo.Common.Entities;
using System.Reflection;
using T2V.SharePoint.Common.Utilities;
using T2V.SharePoint.Common.Helpers;
using T2V.SharePoint.Common.Extensions;
using PepsiCo.Common;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Navigation;
using Microsoft.SharePoint.Publishing.Navigation;

namespace PepsiCo.Intranet.Features.PepsiCo.RootWeb.Data
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("aa540f34-5d34-4c84-a02e-94579998c8a1")]
    public class PepsiCoRootWebDataEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            var web = properties.Feature.Parent as SPWeb;

            ProvisionMegaMenu(web);
            ProvisionQuickLaunch(web);

            ProvisionIntroductionPage(web);
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        //public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}


        private void ProvisionMegaMenu(SPWeb web)
        {
            try
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                string xml = assembly.GetResourceTextFile("PepsiCo.Intranet.XMLCustomSettings.MegaMenu.xml");

                var megaMenuSections = SerializationHelper.DeserializeFromXml<MegaMenuSectionDefinitionCollection>(xml);
                AddMegaMenu(web, megaMenuSections);

            }
            catch (Exception ex)
            {
                Utility.LogError(ex.Message, "PepsiCoRootWebDataEventReceiver ProvisionMegaMenu");
            }
        }

        private void AddMegaMenu(SPWeb web, MegaMenuSectionDefinitionCollection megaMenuSections)
        {
            try
            {
                var listMenuSection = Utility.GetListFromURL(PepsiCoConstants.MegaMenuSection.LIST_URL, web);
                var listMenuItem = Utility.GetListFromURL(PepsiCoConstants.MegaMenuItem.LIST_URL, web);

                if (listMenuSection != null && listMenuItem != null)
                {
                    foreach (var menuSection in megaMenuSections)
                    {
                        SPListItem itemSec = listMenuSection.Items.Add();
                        itemSec["Title"] = menuSection.Section.Trim();
                        itemSec["Hyperlink"] = menuSection.Hyperlink.Trim() != "#" ? (web.ServerRelativeUrl.TrimEnd('/') + menuSection.Hyperlink) : "#";
                        itemSec["ItemOrder"] = menuSection.ItemOrder;
                        itemSec["IsActive"] = menuSection.IsActive;
                        itemSec.SystemUpdate();

                        foreach (var menuItem in menuSection.MenuItems)
                        {
                            SPListItem item = listMenuItem.Items.Add();
                            item["Title"] = menuItem.Title.Trim();
                            item["Hyperlink"] = menuItem.Hyperlink.Trim() != "#" ? (web.ServerRelativeUrl.TrimEnd('/') + menuItem.Hyperlink) : "#";
                            item["Section"] = itemSec.ID;
                            item["SubSection"] = menuItem.SubSection.Trim();
                            item["ItemOrder"] = menuItem.ItemOrder;
                            item["IsActive"] = menuItem.IsActive;
                            item.SystemUpdate();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Utility.LogError(ex.Message, "PepsiCoRootWebDataEventReceiver AddMegaMenu");
            }
        }

        private void ProvisionQuickLaunch(SPWeb web)
        {
            try
            {
                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
                SPNavigationNodeCollection nodes = publishingWeb.Navigation.CurrentNavigationNodes;

                // clearing old quicklaunch navigation nodes
                for (int i = nodes.Count - 1; i >= 0; i--)
                {
                    nodes[i].Delete();
                }

                // setting quick launch navigation nodes
                Assembly assembly = Assembly.GetExecutingAssembly();
                string xml = assembly.GetResourceTextFile("PepsiCo.Intranet.XMLCustomSettings.CustomQuickLaunch_RootSite.xml");

                var quickLaunchItems = SerializationHelper.DeserializeFromXml<CustomQuickLaunchItemDefinitionCollection>(xml);

                foreach (var navItem in quickLaunchItems)
                {
                    SPNavigationNode navNode = SPNavigationSiteMapNode.CreateSPNavigationNode(
                        navItem.Title,
                        web.Url.TrimEnd('/') + "/" + navItem.Hyperlink.TrimStart('/'),
                        navItem.IsHeading ? NodeTypes.Heading : NodeTypes.AuthoredLinkPlain,
                        nodes);

                    if (navItem.IsHeading)
                    {
                        foreach (var link in navItem.Links)
                        {
                            SPNavigationNode navSubNode = SPNavigationSiteMapNode.CreateSPNavigationNode(
                            link.Title,
                            web.Url.TrimEnd('/') + "/" + link.Hyperlink.TrimStart('/'),
                            NodeTypes.AuthoredLinkPlain,
                            navNode.Children);
                            navSubNode.Update();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Utility.LogError(ex.Message, "PepsiCoRootWebDataEventReceiver ProvisionQuickLaunch");
            }
        }

        private void ProvisionIntroductionPage(SPWeb web)
        {
            web.AllowUnsafeUpdates = true;

            try
            {
                SPList list = web.Lists.TryGetList("Pages");

                if (list != null)
                {
                    String url = list.RootFolder.ServerRelativeUrl.ToString();

                    PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);

                    PageLayout[] layouts = publishingWeb.GetAvailablePageLayouts();

                    PageLayout layout = null;

                    foreach (PageLayout pl in layouts)
                    {
                        if (pl.Name.Equals("BlankWebPartPage.aspx", StringComparison.InvariantCultureIgnoreCase))
                        {
                            layout = pl;
                            break;
                        }
                    }

                    string pageName = "Introduction.aspx";

                    PublishingPage newPage = publishingWeb.GetPublishingPages().Add(pageName, layout);
                    newPage.Title = "Company introduction for internal audience";
                    newPage.Update();

                    var folder = web.RootFolder;
                    folder.WelcomePage = newPage.Url;
                    folder.Update();

                    //Now we can checkin the newly created page to the "Pages" library
                    //SPFile pageFile = newPage.ListItem.File;
                    //if (pageFile.CheckOutType != SPFile.SPCheckOutType.None)
                    //{
                    //    pageFile.CheckIn("CheckedIn");
                    //    pageFile.Publish("publihsed");
                    //}
                }
            }
            catch (Exception ex)
            {
                Utility.LogError(ex.Message, "PepsiCoRootWebDataEventReceiver ProvisionIntroductionPage");
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }
    }
}
